package com.iflytek.zwxu.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.iflyteck.zwxu.domain.User;
import com.iflytek.zwxu.api.UserService;
import com.iflytek.zwxu.domin.BaseResult;
import com.iflytek.zwxu.domin.UserVO;

public class UserServiceImpl implements UserService {
	
	private MongoTemplate mongoTemplate;  
	
	public MongoTemplate getMongoTemplate() {
		return mongoTemplate;
	}

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	

	public List<UserVO> getUsers() {
		
		List<User> list = getMongoTemplate().find(new Query(), User.class);
		List<UserVO> newList = new ArrayList<UserVO>();
		for(User u:list)
		{
			UserVO vo = new UserVO();
			BeanUtils.copyProperties(u, vo);
			newList.add(vo);
		}
		return newList;    
	}

	public BaseResult insert(UserVO vo) {
		BaseResult result = new BaseResult();
		try
		{
			User u = new User();
			BeanUtils.copyProperties(vo, u);
			System.out.print(u.getName());
			getMongoTemplate().insert(u);
			result.setSuccess(true);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}
	
	public UserVO queryById(String id) {
        Query query = new Query();
        Criteria criteria = Criteria.where("_id").is(id);
        query.addCriteria(criteria);
        User u = this.mongoTemplate.findOne(query, User.class);
        UserVO vo = new UserVO();
		BeanUtils.copyProperties(u, vo);
        return vo;
    }

	public BaseResult update(String id,String name) {
		BaseResult result = new BaseResult();
		try
		{
			getMongoTemplate().upsert(new Query(Criteria.where("id").is(id)), new Update().set("name", name), User.class);
			result.setSuccess(true);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}

	public BaseResult delete(String id) {
		BaseResult result = new BaseResult();
		try
		{
			mongoTemplate
			.remove(new Query(Criteria.where("id").is(id)), User.class);
			/*Criteria criteria = Criteria.where("id").is(id);     
	        if(criteria == null){     
	             Query query = new Query(criteria);     
	             if(query != null && getMongoTemplate().findOne(query, User.class) != null)     
	                 getMongoTemplate().remove(getMongoTemplate().findOne(query, User.class));     
	        }     */
			result.setSuccess(true);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}

}
